package dao;

import bean.User;
import util.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class UserDao {

    Connection con = null;
    ResultSet rs = null;
    PreparedStatement pstm = null;
    User login = null;
    int row = 0;

    public User login(String username, String password) {
        try{
            // 1.获取数据库连接
            con = JDBCUtil.getCon();
            // 2.定义登陆的sql语句
            String sql = "select * from t_user where username=? and password=?" ;
            // 3.获取预处理对象
            pstm = con.prepareStatement(sql);
            // 4.传参
            pstm.setObject(1,username);
            pstm.setObject(2,password);
            // 5.执行查询
            rs = pstm.executeQuery();
            // 6.解析结果集
            if (rs.next()){
                login = new User();
                // 从结果集中获取数据，封装到实体类中
                login.setUid(rs.getInt("uid"));
                login.setUsername(rs.getString("username"));
                login.setPassword(rs.getString("password"));
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        return login;
    }

    public int register(User user) {
        try{
            // 1.获取数据库连接
            con = JDBCUtil.getCon();
            // 2.定义注册的新增sql语句
            String sql = "insert into t_user(username,password) values(?,?)" ;
            // 3.获取预处理对象
            pstm = con.prepareStatement(sql);
            // 4.传参
            pstm.setObject(1,user.getUsername());
            pstm.setObject(2,user.getPassword());
            // 5.执行更新（增删改）
            row = pstm.executeUpdate();
        }catch (Exception e){
            e.printStackTrace();
        } finally {
            JDBCUtil.close(con,pstm);
        }

        return row;
    }
}
